package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.model.dto.BindTeachplanMediaDto;
import com.xuecheng.content.model.dto.SaveTeachplanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.service.TeachplanService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Mr.M
 * @version 1.0
 * @description 课程计划service接口实现类
 * @date 2022/9/9 11:14
 */
@Service
public class TeachplanServiceImpl implements TeachplanService {

    @Autowired
    TeachplanMapper teachplanMapper;
    @Autowired
    private TeachplanMediaMapper teachplanMediaMapper;

    @Override
    public List<TeachplanDto> findTeachplanTree(long courseId) {
        return teachplanMapper.selectTreeNodes(courseId);
    }

    @Transactional
    @Override
    public void saveTeachplan(SaveTeachplanDto teachplanDto) {

        //课程计划id
        Long id = teachplanDto.getId();
        //修改课程计划
        if(id!=null){
            Teachplan teachplan = teachplanMapper.selectById(id);
            BeanUtils.copyProperties(teachplanDto,teachplan);
            teachplanMapper.updateById(teachplan);
        }else{
            //取出同父同级别的课程计划数量
            int count = getTeachplanCount(teachplanDto.getCourseId(), teachplanDto.getParentid());
            Teachplan teachplanNew = new Teachplan();
            //设置排序号
            teachplanNew.setOrderby(count+1);
            BeanUtils.copyProperties(teachplanDto,teachplanNew);

            teachplanMapper.insert(teachplanNew);
        }
    }

    @Override
    @Transactional
    public void deleteTeachplan(Long id) {
        // 根据Id查看树节点
        Teachplan teachplan = teachplanMapper.selectById(id);
        if (teachplan.getGrade() == 1 && teachplan.getParentid() == 0) {
            //查看是否有小节
            Integer count =  teachplanMapper.selectCountById(id);
            if (count > 0) {
                throw new XueChengPlusException("该课程计划下有子节点，无法删除");
            }
            // 删除树节点
            teachplanMapper.deleteById(id);
        }
        // 删除树节点
        teachplanMapper.deleteById(id);
        // 第二级别的小节，查看是否有关联的视频信息
        TeachplanMedia teachplanMedia = teachplanMediaMapper.selectOne(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId, id));
        if (teachplanMedia != null) {
            teachplanMediaMapper.deleteById(teachplanMedia.getId());
        }
    }

    @Override
    public void moveTeachplan(String move, Long id) {
        // 获取课程计划章节
        Teachplan teachplan = teachplanMapper.selectById(id);

        // 获取排序字段值
        Integer orderby = teachplan.getOrderby();
        Long courseId = teachplan.getCourseId();
        Integer grade = teachplan.getGrade();
        Long parentId = teachplan.getParentid();

        // 判断move是上移还是下移
        if (move.equals("moveup")) { // 上移，根据排序字段值-1，找到上面的章节
            exchange(teachplan, orderby, courseId, grade, parentId, orderby - 1);
        } else if (move.equals("movedown")) { // 下移，根据排序字段值+1，找到下面的章节
            exchange(teachplan, orderby, courseId, grade, parentId, orderby + 1);
        }
    }

    private void exchange(Teachplan teachplan, Integer orderby, Long courseId, Integer grade,
                          Long parentId, Integer orderby1) {
        Teachplan teachplan1 = teachplanMapper.selectOne(new LambdaQueryWrapper<Teachplan>()
                .eq(Teachplan::getOrderby, orderby1)
                .eq(Teachplan::getCourseId, courseId)
                .eq(Teachplan::getGrade, grade)
                .eq(Teachplan::getParentid, parentId));

        // 处理最上端或最下端出现null的情况
        if (teachplan1 == null) {
            return;
        }

        // 把排序字段值交换
        teachplan.setOrderby(orderby1);
        teachplan1.setOrderby(orderby);
        teachplanMapper.updateById(teachplan);
        teachplanMapper.updateById(teachplan1);
    }

    /**
     * @description 获取最新的排序号
     * @param courseId  课程id
     * @param parentId  父课程计划id
     * @return int 最新排序号
     * @author Mr.M
     * @date 2022/9/9 13:43
     */
    private int getTeachplanCount(long courseId,long parentId){
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId,courseId);
        queryWrapper.eq(Teachplan::getParentid,parentId);
        Integer count = teachplanMapper.selectCount(queryWrapper);
        return count;
    }

    @Transactional
    @Override
    public TeachplanMedia associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {
        //教学计划id
        Long teachplanId = bindTeachplanMediaDto.getTeachplanId();
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if(teachplan==null){
            XueChengPlusException.cast("教学计划不存在");
        }
        Integer grade = teachplan.getGrade();
        if(grade!=2){
            XueChengPlusException.cast("只允许第二级教学计划绑定媒资文件");
        }
        //课程id
        Long courseId = teachplan.getCourseId();
        //先删除原来该教学计划绑定的媒资
        teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId,teachplanId));
        //再添加教学计划与媒资的绑定关系
        TeachplanMedia teachplanMedia = new TeachplanMedia();
        teachplanMedia.setCourseId(courseId);
        teachplanMedia.setTeachplanId(teachplanId);
        teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());
        teachplanMedia.setMediaId(bindTeachplanMediaDto.getMediaId());
        teachplanMedia.setCreateDate(LocalDateTime.now());
        teachplanMediaMapper.insert(teachplanMedia);
        return teachplanMedia;
    }


}